<?php




namespace app\controller\api\user;

use app\common\dao\store\service\StoreServiceDao;
use app\common\repositories\MiniShopRepository;
use app\common\repositories\store\order\StoreCartRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\store\service\StoreServiceRepository;
use app\common\repositories\store\shipping\ShippingTemplateRepository;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\controller\merchant\Common;
use app\validate\merchant\StoreProductValidate;
use app\validate\admin\StoreCategoryValidate;
use app\validate\merchant\StoreServiceValidate;
use crmeb\basic\BaseController;
use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\response\Json;

class Admin extends BaseController
{
    protected $merId;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $user = $this->request->userInfo();
        if (isset($user->service->customer) && $user->service->customer == 1) {
            $this->merId = $user->service->mer_id;
        } else {
            throw new HttpResponseException(app('json')->fail('没有权限'));
        }
    }

    public function customerList(StoreServiceRepository $repository)
    {
        $where = $this->request->params(['keyword', 'status']);
        [$page, $limit] = $this->getPage();
        $where['mer_id'] = $this->merId;
        return app('json')->success($repository->getList($where, $page, $limit));
    }

    public function customerDetail($id, StoreServiceDao $dao)
    {
        $service = $dao->getWith($id, ['user' => function ($query) {
            $query->field('avatar,uid');
        }])->toArray();
        $service['uid'] = ['id' => $service['uid'], 'src' => $service['user']['avatar']];
        unset($service['user']);
        return app('json')->success($service);
    }

    public function customerDel($id, StoreServiceRepository $repository)
    {
        if (!$repository->merExists($this->merId, $id))
            return app('json')->fail('数据不存在');
        $repository->delete($id);
        return app('json')->success('删除成功');
    }

    public function customerCreate(StoreServiceValidate $validate, StoreServiceRepository $repository)
    {
        $data = $this->customerCheck($validate);
        if (!$data) return app('json')->fail('用户不存在');
        $data['mer_id'] = $this->merId;
        if ($repository->isBindService($data['uid']) || $repository->issetService($data['mer_id'], $data['uid']))
            return app('json')->fail('该用户已绑定客服');
        $repository->create($data);
        return app('json')->success('添加成功');
    }

    public function customerUpdate($id, StoreServiceValidate $validate, StoreServiceRepository $repository)
    {
        $data = $this->customerCheck($validate);
        if (!$data) return app('json')->fail('用户不存在');
        if (!$repository->merExists($merId = $this->merId, $id))
            return app('json')->fail('数据不存在');
        if ($repository->isBindService($data['uid'], $id) || $repository->issetService($merId, $data['uid'], $id))
            return app('json')->fail('该用户已绑定客服');
        $repository->update($id, $data);
        return app('json')->success('修改成功');
    }

    public function customerCheck(StoreServiceValidate $validate)
    {
        $data = $this->request->params([['uid', []], 'nickname', 'status', 'customer', 'is_verify', 'category', 'goods', ['clerk', 0], 'notify', 'avatar', 'phone', ['sort', 0]]);
        $validate->check($data);
        $avatar = \app\common\model\user\User::getDB()->where('uid', $data['uid']['id'])->value('avatar');
        if (empty($avatar)) return false;
        if (!$data['avatar']) $data['avatar'] = $avatar;
        $data['uid'] = $data['uid']['id'];
        return $data;
    }

    public function cateList(StoreCategoryRepository $repository)
    {
        return app('json')->success($repository->getFormatList($this->merId));
    }

    public function cateDetail($id, StoreCategoryRepository $repository)
    {
        if (!$repository->merExists($this->merId, $id))
            return app('json')->fail('数据不存在');
        return app('json')->success($repository->get($id));
    }

    public function cateDel($id, StoreCategoryRepository $repository)
    {
        if (!$repository->merExists($this->merId, $id))
            return app('json')->fail('数据不存在');
        if ($repository->hasChild($id))
            return app('json')->fail('该分类存在子集，请先处理子集');

        $repository->delete($id);
        return app('json')->success('删除成功');
    }

    public function cateCreate(StoreCategoryValidate $validate, StoreCategoryRepository $repository)
    {
        $data = $this->cateCheck($validate);
        $data['cate_name'] = trim($data['cate_name']);
        if($data['cate_name'] == '')  return app('json')->fail('分类名不可为空');
        if ($data['pid'] && !$repository->merExists($this->merId, $data['pid']))
            return app('json')->fail('上级分类不存在');
        if ($data['pid'] && !$repository->checkLevel($data['pid'],0,$this->merId))
            return app('json')->fail('不可添加更低阶分类');
        $data['mer_id'] = $this->merId;
        $repository->create($data);
        return app('json')->success('添加成功');
    }

    public function cateUpdate($id,StoreCategoryValidate $validate, StoreCategoryRepository $repository)
    {
        $data = $this->cateCheck($validate);
        if(!$repository->checkUpdate($id,$data['pid'])){
            if (!$repository->merExists($this->merId, $id))
                return app('json')->fail('数据不存在');
            if ($data['pid'] && !$repository->merExists($this->merId, $data['pid']))
                return app('json')->fail('上级分类不存在');
            if ($data['pid'] && !$repository->checkLevel($data['pid'],0,$this->merId))
                return app('json')->fail('不可添加更低阶分类');
            if (!$repository->checkChangeToChild($id,$data['pid']))
                return app('json')->fail('无法修改到当前分类到子集，请先修改子类');
            if (!$repository->checkChildLevel($id,$data['pid']))
                return app('json')->fail('子类超过最低限制，请先修改子类');
        }
        $repository->update($id,$data);
        return app('json')->success('编辑成功');
    }

    public function cateCheck(StoreCategoryValidate $validate)
    {
        $data = $this->request->params(['pid','cate_name','is_show','pic','sort']);
        $validate->check($data);
        return $data;
    }

    public function goodsList(ProductRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['cate_id','keyword',['type',1],'mer_cate_id','is_gift_bag']);
        $where = array_merge($where,$repository->switchType($where['type'],$this->merId,0));
        return app('json')->success($repository->getList($this->merId,$where, $page, $limit));
    }

    public function goodsDetail($id, ProductRepository $repository)
    {
        if($id && !$repository->merExists($this->merId,$id))
            return app('json')->fail('数据不存在');
        $data['productInfo'] = $id ? $repository->getAdminOneProduct($id,null) : false;
        $cateRepository = app()->make(StoreCategoryRepository::class);
        $data['platCate'] = $cateRepository->getList();
        $data['merCate'] = $cateRepository->getTreeList($this->merId);
        $data['brandList'] = $cateRepository->getBrandList();
        $data['shipList'] = app()->make(ShippingTemplateRepository::class)->getList($this->merId);
        return app('json')->success($data);
    }

    public function goodsCreate(StoreProductValidate $validate, ProductRepository $repository)
    {
        $merRepository = app()->make(MerchantRepository::class);
        $merchant = $merRepository->get($this->merId);
        $data = $this->goodsCheck($validate);
        $data['mer_id'] = $this->merId;
        if ($data['is_gift_bag'] && !$repository->checkMerchantBagNumber($data['mer_id'])) return app('json')->fail('礼包数量超过数量限制');
        $repository->check($data,$this->merId);
        $data['status'] = $merchant->is_audit ? 0 : 1;
        $data['mer_status'] = ($merchant['is_del'] || !$merchant['mer_state'] || !$merchant['status']) ? 0 : 1;
        $id = $repository->create($data,0);
        app()->make(MiniShopRepository::class)->setProduct($id);
        return app('json')->success('添加成功');
    }

    public function goodsUpdate($id,StoreProductValidate $validate, ProductRepository $repository)
    {
        $merRepository = app()->make(MerchantRepository::class);
        $merchant = $merRepository->get($this->merId);
        $data = $this->goodsCheck($validate);
        if(!$repository->merExists($this->merId,$id))
            return app('json')->fail('数据不存在');
        $repository->check($data,$this->merId);
        $pro = $repository->getWhere(['product_id' => $id]);
        if($pro->status == -2){
            $data['status'] = 0;
        }else{
            $data['status'] = $merchant->is_audit ? 0 : 1;
        }
        $data['mer_status'] = ($merchant['is_del'] || !$merchant['mer_state'] || !$merchant['status']) ? 0 : 1;
        unset($data['is_gift_bag']);
        $repository->edit($id,$data,$this->merId,0);
        app()->make(MiniShopRepository::class)->setProduct($id);
        return app('json')->success('编辑成功');
    }

    public function goodsCheck(StoreProductValidate $validate)
    {
        $params = [
            "image", "slider_image", "store_name", "store_info", "keyword", "bar_code", "brand_id",
            "cate_id", "mer_cate_id", "unit_name", "sort" , "is_show", "is_good",'is_gift_bag',
            "video_link", "temp_id", "content", "spec_type","extension_type", "attr", "attrValue",['give_coupon_ids',[]]
        ];
        $data = $this->request->params($params);
        $validate->check($data);
        return $data;
    }

    public function goodsStatus($id, ProductRepository $repository)
    {
        $status = $this->request->param('status', 0) == 1 ? 1 : 0;
        if(!$repository->merExists($this->merId,$id))
            return app('json')->fail('数据不存在');
        $repository->switchStatus([$id], ['is_show' => $status]);
        app()->make(MiniShopRepository::class)->setStatus($id, $status);
        return app('json')->success('修改成功');
    }

    public function goodsDel($id, ProductRepository $repository)
    {
        if(!$repository->merExists($this->merId,$id))
            return app('json')->fail('数据不存在');
        if($repository->getWhereCount(['product_id' => $id,'is_show' => 1,'status' => 1]))
            return app('json')->fail('商品上架中');
        $repository->delete($id);
        return app('json')->success('转入回收站');
    }

    public function goodsRes($id, ProductRepository $repository)
    {
        if(!$repository->merDeleteExists($this->merId,$id))
            return app('json')->fail('只能删除回收站的商品');
        $repository->restore($id);
        return app('json')->success('商品已恢复');
    }

    public function goodsDelete($id, ProductRepository $repository)
    {
        if(!$repository->merDeleteExists($this->merId,$id))
            return app('json')->fail('只能删除回收站的商品');
        if(app()->make(StoreCartRepository::class)->getProductById($id))
            return app('json')->fail('商品有被加入购物车不可删除');
        $repository->destory($id);
        return app('json')->success('删除成功');
    }

    public function orderStatistics(StoreOrderRepository $repository)
    {
        $order = $repository->OrderTitleNumber($this->merId, null);
        $common = app()->make(Common::class);
        $data = [];
        $data['today'] = $common->mainGroup('today', $this->merId);
        $data['yesterday'] = $common->mainGroup('yesterday', $this->merId);
        $data['month'] = $common->mainGroup('month', $this->merId);
        return app('json')->success(compact('order', 'data'));
    }

    public function orderDetail(StoreOrderRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        list($start, $stop) = $this->request->params([
            ['start', strtotime(date('Y-m'))],
            ['stop', time()],
        ], true);
        if ($start == $stop) return app('json')->fail('参数有误');
        if ($start > $stop) {
            $middle = $stop;
            $stop = $start;
            $start = $middle;
        }
        $where = $this->request->has('start') ? ['dateRange' => compact('start', 'stop')] : [];
        $list = $repository->orderGroupNumPage($where, $page, $limit, $this->merId);
        return app('json')->success($list);
    }

    public function orderList(StoreOrderRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['status']);
        $where['mer_id'] = $this->merId;
        $where['is_del'] = 0;
        return app('json')->success($repository->merchantGetList($where, $page, $limit));
    }

    public function order($id, StoreOrderRepository $repository)
    {
        $detail = $repository->getDetail($id);
        if (!$detail)
            return app('json')->fail('订单不存在');
        if ($detail['mer_id'] != $this->merId)
            return app('json')->fail('没有权限');
        return app('json')->success($detail->toArray());
    }


    protected function checkOrderAuth($id)
    {
        if (!app()->make(StoreOrderRepository::class)->existsWhere(['mer_id' => $this->merId, 'order_id' => $id]))
            throw new ValidateException('没有权限');
    }

    public function mark($id, StoreOrderRepository $repository)
    {
        $this->checkOrderAuth($id);
        $data = $this->request->params(['remark']);
        $repository->update($id, $data);
        return app('json')->success('备注成功');
    }

    public function price($id, StoreOrderRepository $repository)
    {
        $this->checkOrderAuth($id);

        $data = $this->request->params(['total_price', 'pay_postage']);

        if ($data['total_price'] < 0 || $data['pay_postage'] < 0)
            return app('json')->fail('金额不可未负数');
        if (!$repository->merStatusExists((int)$id, $this->merId))
            return app('json')->fail('订单信息或状态错误');
        $repository->eidt($id, $data);
        return app('json')->success('修改成功');
    }

    public function delivery($id, StoreOrderRepository $repository)
    {
        $this->checkOrderAuth($id);
        if (!$repository->merDeliveryExists((int)$id, $this->merId))
            return app('json')->fail('订单信息或状态错误');
        $data = $this->request->params(['delivery_type', 'delivery_name', 'delivery_id']);
        if (!in_array($data['delivery_type'], [1, 2, 3]))
            return app('json')->fail('发货类型错误');
        $repository->delivery($id, $data);
        return app('json')->success('发货成功');
    }

    public function payPrice(StoreOrderRepository $repository)
    {
        list($start, $stop, $month) = $this->request->params([
            ['start', strtotime(date('Y-m'))],
            ['stop', time()],
            'month'
        ], true);

        if ($month) {
            $start = date('Y/m/d', strtotime(getStartModelTime('month')));
            $stop = date('Y/m/d H:i:s', strtotime('+ 1day'));
            $front = date('Y/m/d', strtotime('first Day of this month', strtotime('-1 day', strtotime('first Day of this month'))));
            $end = date('Y/m/d H:i:s', strtotime($start . ' -1 second'));
        } else {
            if ($start == $stop) return app('json')->fail('参数有误');
            if ($start > $stop) {
                $middle = $stop;
                $stop = $start;
                $start = $middle;
            }
            $space = bcsub($stop, $start, 0);//间隔时间段
            $front = bcsub($start, $space, 0);//第一个时间段

            $front = date('Y/m/d H:i:s', $front);
            $start = date('Y/m/d H:i:s', $start);
            $stop = date('Y/m/d H:i:s', $stop);
            $end = date('Y/m/d H:i:s', strtotime($start . ' -1 day'));
        }
        $frontPrice = $repository->dateOrderPrice($front . '-' . $end, $this->merId);
        $afterPrice = $repository->dateOrderPrice($start . '-' . date('Y/m/d H:i:s', strtotime($stop . '-1 day')), $this->merId);
        $chartInfo = $repository->chartTimePrice($start, date('Y/m/d H:i:s', strtotime($stop . '-1 day')), $this->merId);
        $data['chart'] = $chartInfo;//营业额图表数据
        $data['time'] = $afterPrice;//时间区间营业额
        $increase = (float)bcsub((string)$afterPrice, (string)$frontPrice, 2); //同比上个时间区间增长营业额
        $growthRate = abs($increase);
        if ($growthRate == 0) $data['growth_rate'] = 0;
        else if ($frontPrice == 0) $data['growth_rate'] = $growthRate * 100;
        else $data['growth_rate'] = (int)bcmul((string)bcdiv((string)$growthRate, (string)$frontPrice, 2), '100', 0);//时间区间增长率
        $data['increase_time'] = abs($increase); //同比上个时间区间增长营业额
        $data['increase_time_status'] = $increase >= 0 ? 1 : 2; //同比上个时间区间增长营业额增长 1 减少 2

        return app('json')->success($data);
    }

    /**
     * @param StoreOrderRepository $repository
     * @return Json
     * @author xaboy
     * @day 2020/8/27
     */
    public function payNumber(StoreOrderRepository $repository)
    {
        list($start, $stop, $month) = $this->request->params([
            ['start', strtotime(date('Y-m'))],
            ['stop', time()],
            'month'
        ], true);

        if ($month) {
            $start = date('Y/m/d', strtotime(getStartModelTime('month')));
            $stop = date('Y/m/d H:i:s', strtotime('+ 1day'));
            $front = date('Y/m/d', strtotime('first Day of this month', strtotime('-1 day', strtotime('first Day of this month'))));
            $end = date('Y/m/d H:i:s', strtotime($start . ' -1 second'));
        } else {
            if ($start == $stop) return app('json')->fail('参数有误');
            if ($start > $stop) {
                $middle = $stop;
                $stop = $start;
                $start = $middle;
            }
            $space = bcsub($stop, $start, 0);//间隔时间段
            $front = bcsub($start, $space, 0);//第一个时间段

            $front = date('Y/m/d H:i:s', $front);
            $start = date('Y/m/d H:i:s', $start);
            $stop = date('Y/m/d H:i:s', $stop);
            $end = date('Y/m/d H:i:s', strtotime($start . ' -1 day'));
        }
        $frontNumber = $repository->dateOrderNum($front . '-' . $end, $this->merId);
        $afterNumber = $repository->dateOrderNum($start . '-' . date('Y/m/d H:i:s', strtotime($stop . '-1 day')), $this->merId);
        $chartInfo = $repository->chartTimeNum($start . '-' . date('Y/m/d H:i:s', strtotime($stop . '-1 day')), $this->merId);
        $data['chart'] = $chartInfo;//订单数图表数据
        $data['time'] = $afterNumber;//时间区间订单数
        $increase = $afterNumber - $frontNumber; //同比上个时间区间增长订单数
        $growthRate = abs($increase);
        if ($growthRate == 0) $data['growth_rate'] = 0;
        else if ($frontNumber == 0) $data['growth_rate'] = $growthRate * 100;
        else $data['growth_rate'] = (int)bcmul((string)bcdiv((string)$growthRate, (string)$frontNumber, 2), '100', 0);//时间区间增长率
        $data['increase_time'] = abs($increase); //同比上个时间区间增长营业额
        $data['increase_time_status'] = $increase >= 0 ? 1 : 2; //同比上个时间区间增长营业额增长 1 减少 2

        return app('json')->success($data);
    }
}
